﻿/* 
 * Shuriken is the legal property of its developers. Please refer to the
 * COPYRIGHT file distributed with this
 * source distribution.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Shuriken.Core.Preferences
{

    public delegate void PreferenceChangedDelegate(object sender, PreferenceChangedEventArgs args);

    public class Preferences : IPreferences
    {
        IPreferencesBackend backend;
        public event PreferenceChangedDelegate PreferenceChanged;

        public Preferences(string name)
            : this(new ConfigPreferencesBackend(name))
        {
        }

        public Preferences(IPreferencesBackend back)
        {
            backend = back;
        }

        #region IPreferences Members

        public object this[string key]
        {
            get
            {
                return Get<object>(key, "");
            }
            set
            {
                Set<object>(key, value);
            }
        }

        public T Get<T>(string key, T defaultValue)
        {
            bool success;
            T value;
            success = backend.TryGet<T>(key, out value);

            if (!success)
            {
                value = defaultValue;
                Set(key, value);
            }

            return value;
        }

        public void Set<T>(string key, T value)
        {
            if (backend.TrySet<T>(key, value))
            {
                if (PreferenceChanged != null)
                {
                    PreferenceChangedEventArgs args = new PreferenceChangedEventArgs(key, value);
                    PreferenceChanged(this, args);
                }
            }
        }

        #endregion
    }
}
